import os
import os.path


class Transfer:
    """
    @author:syd
    @time:2020/2/10
    @content:将指定的.ui文件转换为.py文件
    """
    def __init__(self):
        # UI 文件所在的路径
        self.Dir = './'
        # 文件存放列表
        self.list = []

        self.listUIFile()

    def listUIFile(self):
        """
        @content:列出目录下的所有UI文件，并存放到list列表中
        """
        files = os.listdir(self.Dir)
        for filename in files:
            # print(dir + os.sep + f)
            # print(filename)
            if os.path.splitext(filename)[1] == '.ui':
                self.list.append(filename)

    @staticmethod
    def transPyFile(filename):
        """
        @content:把扩展名为.ui的文件改成扩展名为.py的文件
        """
        return os.path.splitext(filename)[0] + '.py'

    def printUI(self):
        """
        @content:展示该目录下所有.ui文件的名称及序号
        """
        id = range(1, len(self.list) + 1, 1)
        zipped = zip(id, self.list)
        for id, uifile in zipped:
            print(str(id) + ': ' + uifile)

    def excuteAll(self):
        """
        content:将.ui文件全部转换为.py文件
        """
        try:
            for uifile in self.list:
                pyfile = self.transPyFile(uifile)
                cmd = 'pyuic5 -o {pyfile} {uifile}'.format(pyfile=pyfile, uifile=uifile)
                print(cmd)
                os.system(cmd)
            print("全部文件转换成功")
        except Exception as ex:
            print("转换过程中出现错误，出错原因:" + str(ex))

    def excuteSingle(self, id):
        """
        @content: 将单个.ui文件转换为.py文件
        """
        if id < 1 or id > len(self.list):
            print("找不到" + str(id) + "号文件")
            return -1
        try:
            uifile = self.list[id - 1]
            pyfile = self.transPyFile(uifile)
            cmd = 'pyuic5 -o {pyfile} {uifile}'.format(pyfile=pyfile, uifile=uifile)
            print(cmd)
            os.system(cmd)
            return 1
        except Exception as ex:
            print(ex)

    def runMain(self):
        """
        @content:调用系统命令把UI文件转换为python文件
        """
        str = input("请输入要转换的文件序号：")
        str = str.strip()
        if str == "全部":
            self.excuteAll()
        else:
            try:
                id = str.split(' ')
                flag = 1
                for i in id:
                    if self.excuteSingle(int(i)) == -1:
                        flag = -1
                if flag == 1:
                    print("单个文件执行成功")
            except Exception as ex:
                print("处理单个文件时出现错误，错误原因:" + str(ex))


if __name__ == "__main__":
    """
    @tips：如果想要将全部的.ui转换为.py文件，输入"全部"即可；
            如果想要将其中的某几个.ui文件转换为.py文件，依次输入对应文件名称前边的序号，
            并且每两个序号中间以一个空格分割即可。示例：1 2 3 4
    """
    transfer = Transfer()
    transfer.printUI()
    transfer.runMain()